<?php

namespace app\index\controller;

use think\Controller;

class Index extends Controller
{
    public function index()
    {
        $where = [];
        $cateInfo = null;
        if (input('id')) {
            $where = [
                'cateid' => input('id')
            ];
            $cateInfo = model('Cate')->where('id', input('id'))->value('catename');
        }
        $cateList = model('Cate')->order('id', 'asc')->select();
        $articleList = model('Article')->where($where)->order('id', 'desc')->paginate(5);
        $webInfo = model('System')->find();
        $viewData = [
            'cateInfo' => $cateInfo,
            'cateList' => $cateList,
            'articleList' => $articleList,
            'webInfo' => $webInfo
        ];
        $this->assign($viewData);
        return view();
    }

    public function login()
    {
        if (request()->isAjax()) {
            $data = input('post.');
            $result = model('Member')->login($data);
            if ($result == 1) {
                $this->success('登录成功！', 'index/index/index');
            }else {
                $this->error($result);
            }
        }
        $cateList = model('Cate')->order('id', 'asc')->select();
        $webInfo = model('System')->find();
        $viewData = [
            'cateList' => $cateList,
            'webInfo' => $webInfo
        ];
        $this->assign($viewData);
        return view();
    }

    public function loginout()
    {
        session(null);
        if (session('?username')) {
            $this->error('退出失败！');
        }else {
            $this->success('退出成功！', 'index/index/index');
        }
    }

    public function register()
    {
        if (request()->isAjax()) {
            $data = input('post.');
            $result = model('Member')->register($data);
            if ($result == 1) {
                $this->success('注册成功！', 'index/index/login');
            }else {
                $this->error($result);
            }
        }
        $cateList = model('Cate')->order('id', 'asc')->select();
        $webInfo = model('System')->find();
        $viewData = [
            'cateList' => $cateList,
            'webInfo' => $webInfo
        ];
        $this->assign($viewData);
        return view();
    }

    public function article()
    {
        $cateList = model('Cate')->order('id', 'asc')->select();
        $webInfo = model('System')->find();
        $articleInfo = model('Article')->where('id', input('id'))->find();
        $viewData = [
            'cateList' => $cateList,
            'webInfo' => $webInfo,
            'articleInfo' => $articleInfo
        ];
        $this->assign($viewData);
        return view();
    }
}
